/* eslint-disable react/no-danger */
/* eslint-disable react/prop-types */
/* eslint-disable react/jsx-pascal-case */
import React, { useCallback } from 'react';
import { Select, Loading, Balloon, Button, Tag, Divider } from '@teamix/ui';
import FilePanel from 'components/filePanel';
import { YunxiaoIcon } from '@alife/devops-ui';
import { ENUM } from 'utils/constants.js';
import ListEmpty from 'atComponents/ListEmpty';
import utils from 'utils';
import intl from '../../../../../../locale';
import { returnNumText, returnTypeName } from '../../utils/ahooks';
import track from 'utils/track';
import './index.scss';
import CommitIdAndSrcBtns from 'components/commitIdAndSrcBtns';
import UsersAvatar from '@alife/teamix-at-users-avatar';
import Grammarempty from './grammarEmpty';
import { navigate, navigateOpen } from 'utils/router';
import Pagination from 'components/commonPagination';

const { visibility_levels } = ENUM;
const iconMap = {
  opened: 'pull-request-failed-line',
  reopened: 'pull-request-failed-line',
  accepted: 'pull-request-success-line',
  merged: 'merge-line',
  closed: 'pull-request-closed-line',
};

const iconColorMap = {
  opened: 'green',
  reopened: 'green',
  accepted: 'green',
  merged: 'gray',
  closed: 'red',
};

const textMap = {
  opened: intl.get({
    id: 'code-assets.components.crListItem.EnabledFailedToMeetThe',
    defaultMessage: '已开启·未达到合并要求',
  }),
  reopened: intl.get({
    id: 'code-assets.components.crListItem.EnabledFailedToMeetThe',
    defaultMessage: '已开启·未达到合并要求',
  }),
  accepted: intl.get({
    id: 'code-assets.components.crListItem.EnabledAndCanBeMerged',
    defaultMessage: '已开启·可合并',
  }),
  merged: intl.get({ id: 'code-assets.components.crListItem.Merged', defaultMessage: '已合并' }),
  closed: intl.get({ id: 'code-assets.components.crListItem.Disabled', defaultMessage: '已关闭' }),
};

const { Tooltip } = Balloon;

const Search_left = (props) => {
  const {
    searchType,
    leftLoading,
    leftData,
    leftMatchSelectValue,
    setMatchSelectValue,
    leftDataNum,
    setRoWColSpan,
    rowSpanCol: { middleState },
    leftDataSelectedValue,
    leftDataPage,
    setLeftDataPagination,
    setLeftData,
    headerModeStatus,
  } = props;

  const formatValue = utils.getUrlParam({ name: 'inputtext', type: 'search' });
  const height_cons = leftDataNum > 10 ? 284 : 240;
  const grammarEmptyClick = () => {
    props.getSearchOnChange('README and lang:Markdown');
    props.headerInputStatusChange(false);
    const searchcodestorehousedata = utils.getUrlSearchParam('searchcodestorehousedata') || '';
    if (props.searchType !== 'code') {
      props.setSearchType('code');
    }
    navigate(
      `${window.location.origin}${window.location.pathname}?inputtext=${encodeURIComponent(
        'README and lang:Markdown',
      )}&searchcodestorehousedata=${encodeURIComponent(
        searchcodestorehousedata,
      )}&filter=%7B"type"%3A"code"%7D&is_dsl=${headerModeStatus === 'grammar'}`,
    );
    props.getSearchData();
  };
  const getAvatarname = (type, data) => {
    const { source } = data;
    if (type === 'mr') {
      return (
        <Tooltip
          trigger={
            <YunxiaoIcon
              type={iconMap[source.state]}
              style={{ color: `${iconColorMap[source.state]}` }}
            />
          }
          align="t"
        >
          {textMap[source.state]}
        </Tooltip>
      );
    } else if (type === 'repo') {
      return source.repoName && source.repoName.length > 0
        ? source.repoName.slice(0, 1).toLocaleUpperCase()
        : '';
    } else {
      const value = source.repoPath ? utils.getGroupPath(source.repoPath) : '';
      return value && value.length > 0 ? value.slice(0, 1).toLocaleUpperCase() : '';
    }
  };
  const catAuthor = (data) => {
    // https://codeup.aliyun.com/60485e227fc1eb44d2170347/a1/blame/master/22
    const { source } = data;
    const href = `/${source.repoPath}/blame/${source.branch}/${source.filePath}`;
    return navigateOpen(href);
  };
  const getFilePath = (data) => {
    // https://daily-codeup.aliyun.com/60485e227fc1eb44d2170347/aa2/blob/master/fixtures/flight/server/handler.server.js
    const { source } = data;
    const href = `/${source.repoPath}/blob/${source.branch}/${source.filePath}`;
    return navigateOpen(href);
  };
  const notCodeTitleHref = (type, data) => {
    track({
      action: 'search_result_jump',
      page: 'Search-Page',
      type: returnTypeName(type),
      // 右边选中的筛选类型，代码片段:code_snippet，代码库:code_repo，提交:code_commit，合并请求:code_mr
      control: returnNumText(leftDataNum),
      // default:还没有搜索，none:结果=0，less:0<结果<=10，middle:10<结果<=100，large 结果 > 100
    });
    const { source } = data;
    if (type === 'repo') {
      const href = `/${source.repoPath}`;
      return navigateOpen(href);
    } else if (type === 'mr') {
      const href = `/${source.repoPath}/merge_request/${source.id}`;
      return navigateOpen(href);
    } else if (type === 'commit') {
      const href = `/${source.repoPath}/commit/${source.commitId}`;
      return navigateOpen(href);
    }
  };
  const commitShowHander = (data) => {
    if (!data) return '';
    const artstr = data.split('\n');
    if (artstr.length > 1) {
      artstr.shift();
      return artstr.join('\n');
    } else {
      return artstr.join('\n');
    }
  };
  const searchTypeName = useCallback(() => {
    if (searchType === 'code') {
      return '代码片段';
    } else if (searchType === 'repo') {
      return '代码库';
    } else if (searchType === 'commit') {
      return '提交';
    } else {
      return '合并请求';
    }
  }, [searchType]);
  const pageChange = (current) => {
    const scrool = document.querySelector('.codeup_search_right_con');
    if (scrool) scrool.scrollTop = 0;
    track({
      action: 'pagination_visit',
      page: 'Search-Page',
      type: 'click', // click:点击页码按钮，jump:输入页码跳转
      // eslint-disable-next-line no-nested-ternary
      control: leftDataNum <= 10 ? 'less' : leftDataNum <= 100 ? 'middle' : 'large',
      // default:还没有搜索，none:结果=0，less:0<结果<=10，middle:10<结果<=100，large 结果 > 100
    });
    setLeftDataPagination(current);
  };
  return leftLoading ? (
    <Loading visible={leftLoading} style={{ width: '100%' }} className="teamix-result all-empty" />
  ) : (
    <section
      className={`codeup_search_right_cons ${
        middleState ? 'codeup_search_right_middleState_cons' : ''
      }`}
    >
      {leftData && formatValue ? (
        <div className="codeup_search_right_header">
          <span style={{ fontWeight: 'bold' }}>
            找到 {leftData && leftDataNum ? leftDataNum : 0} 个 {searchTypeName()} 结果
          </span>

          {leftDataNum > 1 && (
            <div className="codeup_search_right_header_select">
              <Select
                value={leftMatchSelectValue}
                onChange={(value) => {
                  let type = 'earliest_update';
                  if (value === 'default') {
                    type = 'best_match';
                  } else if (value === 'updated_at_desc') {
                    type = 'recent_update';
                  }

                  track({
                    action: 'select_sort_type',
                    page: 'Search-Page',
                    type,
                    control: returnNumText(leftDataNum),
                  });
                  setMatchSelectValue(value);
                }}
              >
                <option value="default">最佳匹配</option>
                <option value="updated_at_desc">最近更新</option>
                <option value="updated_at_asc">最早更新</option>
              </Select>
            </div>
          )}
        </div>
      ) : (
        <span> </span>
      )}

      <div
        className="codeup_search_right_con"
        style={{
          maxHeight:
            headerModeStatus === 'grammar' && !formatValue
              ? ''
              : `calc( 100vh - ${height_cons + 40}px )`,
        }}
      >
        <div className="codeup_search_right_con_list">
          {searchType !== 'code' &&
            leftData &&
            leftData.length > 0 &&
            leftData.map((va, index) => {
              const {
                highlightTextMap: { commitMessage, title },
                source,
                source: {
                  commitId,
                  repoPath,
                  createTime,
                  updateTime,
                  authorTime,
                  lastActivityTime,
                  visibilityLevel,
                },
              } = va;
              const visibilityLabel = visibility_levels.find(
                (v) => v.value === visibilityLevel,
              )?.label;
              return (
                <div
                  className="codeup_search_right_con_list_item"
                  key={commitId}
                  onClick={() => notCodeTitleHref(searchType, va)}
                >
                  {searchType !== 'commit' && (
                    <div className="search_list_item_icon">
                      {(searchType === 'repo' || searchType === 'mr') && (
                        <div className={`repo_name ${searchType}`}>
                          <span style={{ whiteSpace: 'nowrap' }}>
                            {getAvatarname(searchType, va)}
                          </span>
                        </div>
                      )}
                    </div>
                  )}
                  <div className="search_list_item_title_main_con">
                    <div className="search_list_item_main_title">
                      {searchType === 'repo' ? (
                        <Tooltip
                          trigger={
                            <span
                              dangerouslySetInnerHTML={{
                                __html:
                                  commitMessage ||
                                  title ||
                                  va.highlightTextMap.repoNameWithNamespace ||
                                  (va.highlightTextMap.repoPath &&
                                    utils.getGroupPath(va.highlightTextMap.repoPath)),
                              }}
                            />
                          }
                          align="t"
                        >
                          {source.repoName}
                        </Tooltip>
                      ) : (
                        <span
                          dangerouslySetInnerHTML={{
                            __html:
                              title ||
                              commitMessage ||
                              (va.highlightTextMap.repoNameWithNamespace &&
                                utils.getGroupPath(va.highlightTextMap.repoNameWithNamespace)) ||
                              (va.highlightTextMap.repoPath &&
                                utils.getGroupPath(va.highlightTextMap.repoPath)),
                          }}
                        />
                      )}
                      {searchType === 'commit' && va.highlightTextMap.commitMessage && (
                        <span
                          className="commit-msg-desc-trigger show-more-span bright"
                          onClick={(e) => {
                            e.stopPropagation();
                            const newData = leftData.map((val) => {
                              if (val.docId === va.docId) {
                                return { ...val, isMsgDescVisible: !va.isMsgDescVisible };
                              } else {
                                return { ...val };
                              }
                            });
                            setLeftData(newData);
                          }}
                        >
                          <YunxiaoIcon type="more-line" className="show-more-icon" />
                        </span>
                      )}
                    </div>
                    {searchType === 'commit' && va.isMsgDescVisible && (
                      <div
                        className="commit-msg-desc"
                        dangerouslySetInnerHTML={{
                          __html: commitShowHander(va.highlightTextMap.commitMessage),
                        }}
                      />
                    )}
                    <div className="search_list_item_subtitle">
                      {searchType === 'repo' && (
                        <Tooltip
                          trigger={
                            <span
                              className="code_name"
                              dangerouslySetInnerHTML={{
                                __html: va.highlightTextMap.description,
                              }}
                            />
                          }
                          align="b"
                        >
                          {va.highlightTextMap?.description?.replace(/<[^>]*>|<\/[^>]*>/gm, '')}
                        </Tooltip>
                      )}
                      {searchType === 'repo' && va.highlightTextMap?.description && (
                        <span style={{ padding: '0 8px' }}>·</span>
                      )}
                      {searchType !== 'repo' && searchType !== 'commit' && (
                        <>
                          <Tooltip
                            trigger={
                              <span className="code_name">
                                {repoPath ? utils.getGroupPath(repoPath) : ''}
                              </span>
                            }
                            align="b"
                          >
                            {repoPath ? utils.getGroupPath(repoPath) : ''}
                          </Tooltip>
                          <span className="desc-divider">·</span>
                        </>
                      )}
                      {source?.sourceBranch && (
                        <>
                          <Tooltip
                            trigger={
                              <span className="code_branch">
                                {source?.sourceBranch && source?.sourceBranch}
                                {source?.sourceBranch && (
                                  <YunxiaoIcon
                                    type="arrow-right-line"
                                    size="small"
                                    className="cr-list-icon"
                                    style={{ margin: '0 3px' }}
                                  />
                                )}
                                {source?.targetBranch && source?.targetBranch}
                              </span>
                            }
                            align="b"
                          >
                            {`从${source?.sourceBranch}合并到 ${source?.targetBranch}`}
                          </Tooltip>
                          <span className="desc-divider">·</span>
                        </>
                      )}
                      <Tooltip
                        trigger={
                          <span className="code_date">
                            {(searchType === 'commit' && source?.author?.avatar && (
                              <img
                                width="24"
                                src={source.author.avatar}
                                style={{ marginRight: 8 }}
                              />
                            )) ||
                              (searchType === 'commit' && (
                                <span style={{ marginLeft: 6, marginRight: 4 }}>
                                  {' '}
                                  <UsersAvatar
                                    dataSource={[source.author]}
                                    size="xs"
                                    borderColor={'#f7f7f7'}
                                  />
                                </span>
                              ))}
                            <span className="text-ellipsis">
                              {source?.author?.name || ''}
                              {source?.author?.name && ' '}
                              {searchType === 'repo' && <span>更新于 </span>}
                              {searchType === 'commit' && <span>提交于 </span>}
                              {searchType !== 'commit' && searchType !== 'repo' && (
                                <span>创建于 </span>
                              )}
                              {searchType === 'mr' && utils.getBeautyTime(createTime)}
                              {searchType === 'repo' && utils.getBeautyTime(lastActivityTime)}
                              {searchType === 'commit' && utils.getBeautyTime(authorTime)}
                              {searchType === 'repo' ||
                              searchType === 'mr' ||
                              searchType === 'commit'
                                ? ''
                                : '天前'}
                            </span>
                          </span>
                        }
                        align="b"
                      >
                        <span>
                          {source?.author?.name || source?.user?.name || ''}
                          {searchType === 'repo' ? (
                            <>
                              <span>更新于</span>
                            </>
                          ) : (
                            '创建于 '
                          )}
                          {searchType === 'mr' && utils.getBeautyTime(createTime)}
                          {searchType === 'repo' && utils.getBeautyTime(lastActivityTime)}
                          {searchType === 'commit' && utils.getBeautyTime(authorTime)}
                          {searchType === 'repo' || searchType === 'mr' || searchType === 'commit'
                            ? ''
                            : '天前'}
                        </span>
                      </Tooltip>
                      {searchType === 'commit' && (
                        <>
                          <span className="desc-divider">·</span>
                          <Tooltip
                            trigger={
                              <span className="code_name">
                                {repoPath ? utils.getGroupPath(repoPath) : ''}
                              </span>
                            }
                            align="b"
                          >
                            {repoPath ? utils.getGroupPath(repoPath) : ''}
                          </Tooltip>
                        </>
                      )}
                    </div>
                    {searchType === 'mr' && (
                      <Tooltip
                        trigger={
                          <span
                            className="mrDesc"
                            dangerouslySetInnerHTML={{
                              __html: va.highlightTextMap.description,
                            }}
                          />
                        }
                        align="b"
                      >
                        {va.highlightTextMap?.description?.replace(/<[^>]*>|<\/[^>]*>/gm, '')}
                      </Tooltip>
                    )}
                  </div>
                  <div className="search_left_commit_section">
                    {searchType === 'commit' && (
                      <CommitIdAndSrcBtns
                        {...{
                          searchCommitBtnShow: true,
                          searchCommitInfo: leftData[index],
                        }}
                      />
                    )}

                    {searchType === 'commit' && (
                      <Tooltip
                        trigger={
                          <Button
                            type="normal"
                            color="gray"
                            component="a"
                            name="folder-line"
                            className="src-btn"
                            onClick={(e) => {
                              e.stopPropagation();
                              const href = `/${source.repoPath}/tree/${source.commitId}`;
                              navigateOpen(href);
                            }}
                          >
                            <YunxiaoIcon type="folder-line" />
                          </Button>
                        }
                        align="b"
                      >
                        {intl.get({
                          id: 'code-assets.components.commitIdAndSrcBtns.srcBtn.ViewSourceFiles',
                          defaultMessage: '查看源文件',
                        })}
                      </Tooltip>
                    )}
                  </div>
                  {searchType === 'repo' && visibilityLabel && (
                    <div className="search_list_item_sub_date">
                      <Tag>{visibilityLabel}</Tag>
                    </div>
                  )}
                  {searchType === 'mr' && (
                    <div className="search_list_item_sub_date">
                      更新于 {searchType === 'mr' && utils.getBeautyTime(updateTime)}
                    </div>
                  )}
                </div>
              );
            })}
        </div>
        {searchType === 'code' &&
          leftData &&
          leftData.length > 0 &&
          leftData.map((va) => {
            const { source } = va;
            const { fileName: higlightFileName } = va.highlightTextMap;
            return (
              <div // codeup_search_right_table Selected ${va.docId} === ${leftDataSelectedValue}
                className={`${
                  va.docId === leftDataSelectedValue
                    ? 'codeup_search_right_table Selected '
                    : 'codeup_search_right_table '
                } ${middleState ? 'left_middle_table_max_width' : null}`}
                key={va.docId}
              >
                <FilePanel>
                  <FilePanel.Header>
                    <div className="codeup_search_right_table_header">
                      <div className="codeup_search_right_table_header_left_title">
                        {!middleState ? (
                          <>
                            <Tooltip
                              needAdjust
                              trigger={
                                <a onClick={() => getFilePath(va)} className="filePath">
                                  <YunxiaoIcon
                                    type="file-2-line"
                                    style={{
                                      marginRight: '8px',
                                      color: 'var(--color-fill1-6, #8b8b8b)',
                                    }}
                                  />
                                  {higlightFileName ? (
                                    <span
                                      dangerouslySetInnerHTML={{
                                        __html: higlightFileName,
                                      }}
                                    />
                                  ) : (
                                    <span>{source.fileName}</span>
                                  )}
                                </a>
                              }
                              align="tr"
                            >
                              {source.filePath}
                            </Tooltip>
                            &nbsp;&nbsp;
                            <Tooltip
                              trigger={
                                <span style={{ color: '#8b8b8b' }}>
                                  {utils.getGroupPath(source.repoPath)}
                                </span>
                              }
                              align="t"
                            >
                              {utils.getGroupPath(source.repoPath)}
                            </Tooltip>
                          </>
                        ) : (
                          <>
                            <div className="middleState_header_title">
                              <div style={{ display: 'flex' }}>
                                <Tooltip trigger={utils.getGroupPath(source.repoPath)} align="t">
                                  {utils.getGroupPath(source.repoPath)}
                                </Tooltip>
                                {'-'}
                                <Tooltip
                                  needAdjust
                                  trigger={
                                    <span onClick={() => getFilePath(va)} className="filePath">
                                      {higlightFileName ? (
                                        <span
                                          dangerouslySetInnerHTML={{
                                            __html: higlightFileName,
                                          }}
                                        />
                                      ) : (
                                        <span>{source.fileName}</span>
                                      )}
                                    </span>
                                  }
                                  align="tr"
                                >
                                  {source.filePath}
                                </Tooltip>
                              </div>
                              <div className="preview_name">提交于 {source.checkinDate}</div>
                            </div>
                          </>
                        )}
                      </div>
                      <div className="codeup_search_right_table_header_right_preview">
                        {!middleState && (
                          <div className="preview_name">提交于 {source.checkinDate}</div>
                        )}
                        <Divider direction="ver" />
                        {!middleState && (
                          <>
                            <Button
                              type="primary"
                              text
                              onClick={() => {
                                track({
                                  action: 'to_view_author',
                                  page: 'Search-Page',
                                  type: '',
                                  control: '',
                                });
                                track({
                                  action: 'to_view_author',
                                  page: 'Search-Page',
                                  type: returnTypeName(searchType),
                                  control: returnNumText(leftDataNum),
                                });
                                catAuthor(va);
                              }}
                            >
                              Blame
                            </Button>
                            <Divider direction="ver" />
                          </>
                        )}
                        <div
                          className="preview_font"
                          onClick={() => {
                            track({
                              action: 'to_view_detail',
                              page: 'Search-Page',
                              type: '',
                              control: '',
                            });
                            track({
                              action: 'to_view_detail',
                              page: 'Search-Page',
                              type: returnTypeName(searchType),
                              control: returnNumText(leftDataNum),
                            });
                            setRoWColSpan(va.docId, props.headerModeStatus);
                          }}
                        >
                          预览
                        </div>
                      </div>
                    </div>
                  </FilePanel.Header>
                  <div className="codeup_search_right_table_con">
                    <FilePanel.Body noPadding>
                      <pre>
                        <code
                          dangerouslySetInnerHTML={{
                            __html: va.highlightTextMap?.clob?.replace('\n', '<br />'),
                          }}
                        />
                      </pre>
                    </FilePanel.Body>
                  </div>
                </FilePanel>
              </div>
            );
          })}
        {leftData && formatValue && leftData.length === 0 && (
          <ListEmpty
            className="search-result-empty-other all-empty"
            imgType="search"
            style={{ height: '100%' }}
            content="找不到匹配的内容"
            description="当前条件下无结果，更换搜索词或筛选条件后再试吧"
          />
        )}
        {headerModeStatus === 'ordinary' && !formatValue && (
          <ListEmpty
            className="search-result-empty-other all-empty"
            imgType="search"
            style={{ height: '100%' }}
            description="支持搜索代码文本、提交、合并请求，让查询更高效"
          />
        )}
        {headerModeStatus === 'grammar' && !formatValue && (
          <Grammarempty grammarEmptyClick={grammarEmptyClick} />
        )}
      </div>
      {leftData && leftData.length > 0 && leftDataNum > 10 && (
        <div className="codeup_search_right_pagination">
          <Pagination
            current={leftDataPage.page}
            total={leftDataNum}
            onChange={pageChange}
            type={middleState ? 'simple' : 'normal'}
          />
        </div>
      )}
    </section>
  );
};

export default Search_left;
